//
//  PaymentVM.swift
//  LeTu
//
//  Created by gy on 2024/1/10.
//

import Foundation

class PaymentVM {
    
    private(set) var scenicModel: ScenicModel
    private(set) var sectionItems = [ListSectionItem]()
    /// 会员管理
    private(set) var vipVM = VipCenterVM()
    /// 优惠券信息
    private var coupons = [MineCouponsModel]()
    private(set) var couponsModel: MineCouponsModel?
    /// 当前选中的价格下标
    var currentPriceIndex = 0

    
    init(scenicModel: ScenicModel) {
        self.scenicModel = scenicModel
        
        updateSectionItmes()
    }
    func updateSectionItmes() {
        sectionItems = [ListSectionItem(title: "景区")]
        
        if vipVM.pricesArr.count > 0 {
            sectionItems.append(ListSectionItem(title: "价格"))
        }
        
        updateCouponsItem()
    }
    /// 计算最优优惠券
    func updateCouponsItem() {
//        if currentPriceIndex < vipVM.pricesArr.count {
//            
//            let priceModel = vipVM.pricesArr[currentPriceIndex]
//            couponsModel = coupons.filter({ $0.money <= priceModel.productPrice }).max(by: { $0.money < $1.money })
//            sectionItems = sectionItems.filter({ $0.title != "优惠券" })
//            if couponsModel != nil {
//                sectionItems.append(ListSectionItem(title: "优惠券"))
//            }
//        }
    }
    /// 获取实付金额
    func getFinalPrice() -> Int {
        
        guard currentPriceIndex < vipVM.pricesArr.count else { return 0 }
        let priceModel = vipVM.pricesArr[currentPriceIndex]
        var finalPrice = priceModel.productPrice
        if let couponsModel = couponsModel {
            finalPrice = finalPrice-couponsModel.money
        }
        return finalPrice
        
    }
    
    /// 获取可用优惠券
    func getCouponList(isLoad: Bool, completeHolder: @escaping NetworkRequestHandle) {
        
        apiProvider.request(api: .getCoupons(params: ["useStatus": 0])) { [weak self] json, jsonArr, code in

            guard let strongSelf = self else { return }

            MYLog("获取优惠券列表：", json)

            var dialog = DialogMessage()

            guard let response = Mapper<ResponseModel>().map(JSON: json) else { return completeHolder(dialog) }
            dialog.code = response.code
            dialog.message = response.msg
            guard let data = response.data as? [[String: Any]] else { return completeHolder(dialog) }

            if dialog.code == 200 {
                strongSelf.coupons = Mapper<MineCouponsModel>().mapArray(JSONArray: data)
            }
            completeHolder(dialog)

        } failureHandler: { error in
            completeHolder(DialogMessage())
        }

    }
    
}

